import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;

public class LoginServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   	doPost(request,response);
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String userName = request.getParameter("login");
    String password = request.getParameter("senha");
	Conexao.getConexao();
	HttpSession session;
	session = request.getSession(true);
   	if (login(userName, password)){
		session.setAttribute("logado",new String("true"));
		response.sendRedirect("principal.jsp");
	}else{
		session.setAttribute("errologin",new String("true"));
		response.sendRedirect("index.jsp");
		}
  }

  public static boolean login(String userName, String password){
    boolean passou = false;
	try {
		Connection con = Conexao.getConexao().getConnection();
		Statement s = con.createStatement();
		String sql = "SELECT id FROM Usuario " +
					 "WHERE login='" + userName + "' AND senha='" + password + "'";
		ResultSet rs = s.executeQuery(sql);
		if (rs.next()) {
			rs.close();
			s.close();
			passou = true;
		}
	}catch (Exception e) {
	}
	return passou;
  }
}